package cn.edu.hhu.teacher.service;

import cn.edu.hhu.Bean.AttendanceTask;
import cn.edu.hhu.teacher.bean.Attendance;
import cn.edu.hhu.teacher.bean.Course;
import cn.edu.hhu.teacher.bean.Student;
import cn.edu.hhu.teacher.bean.Teacher;
import cn.edu.hhu.teacher.dao.AttendanceDao;
import cn.edu.hhu.teacher.dao.CourseDao;
import cn.edu.hhu.teacher.dao.MemberDao;
import cn.edu.hhu.teacher.dao.TaskDao;

import java.util.List;

public class CourseService {
    private CourseDao courseDao = new CourseDao();
    private MemberDao memberDao = new MemberDao();
    private TaskDao taskDao = new TaskDao();
    private AttendanceDao attendanceDao = new AttendanceDao();

    public boolean add(Course course) {
        return courseDao.addCourse(course.getCname(), course.getTid()) == 1;
    }

    public Course get(Teacher teacher, String cid) {
        long id;
        try {
            id = Long.parseLong(cid);
        } catch (NumberFormatException e) {
            return null;
        }
        return courseDao.queryCourseByTidAndCid(teacher.getTid(), id);
    }

    public boolean delete(Course course) {
        return courseDao.deleteCourseByCid(course.getCid()) == 1;
    }

    public List<Student> queryStudents(Course course) {
        return memberDao.queryStudentsByCid(course.getCid());
    }

    public boolean deleteStudent(Course course, String sid) {
        return memberDao.deleteStudentByCidAndSid(course.getCid(), sid) == 1;
    }

    public boolean addStudent(Course course, String sid) {
        return memberDao.addStudentByCidAndSid(course.getCid(), sid) == 1;
    }

    public List<AttendanceTask> queryTasks(Course course) {
        return taskDao.queryTaskByCid(course.getCid());
    }

    public boolean deleteTask(Course course, String tnum) {
        long num;
        try {
            num = Long.parseLong(tnum);
        } catch (NumberFormatException e) {
            return false;
        }
        return taskDao.deleteTaskByCidAndTnum(course.getCid(), num) == 1;
    }

    public boolean addTask(AttendanceTask task) {
        return taskDao.addTask(task.getCid(), task.getTname(), task.getPwd(), task.getStart_time(), task.getEnd_time(), task.getRelease_time()) == 1;
    }

    public List<Attendance> queryAttendances(Course course, String tnum, String tname, String sid, String sname) {
        if (tnum == null || tnum.equals("")) {
            tnum = "%";
        } else {
            tnum = "%" + tnum + "%";
        }
        if (tname == null || tname.equals("")) {
            tname = "%";
        } else {
            tname = "%" + tname + "%";
        }
        if (sid == null || sid.equals("")) {
            sid = "%";
        } else {
            sid = "%" + sid + "%";
        }
        if (sname == null || sname.equals("")) {
            sname = "%";
        } else {
            sname = "%" + sname + "%";
        }
        return attendanceDao.queryAttendance(course.getCid(), tnum, tname, sid, sname);
    }
}
